package cn.net.shuxing.yifu.common.service;

import cn.net.shuxing.yifu.common.bean.UserRealInfo;
import cn.net.shuxing.yifu.common.constant.CodeConst;
import cn.net.shuxing.yifu.common.dto.BaseDto;
import cn.net.shuxing.yifu.common.util.HttpUtils;
import cn.net.shuxing.yifu.common.util.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import cn.net.shuxing.yifu.common.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 人脸识别
 */
@Service
public class FaceVerifyService {

    @Autowired
    private UserRealInfoService userRealInfoService;

    public boolean verify(String img1, String img2)
    {
        String host = "http://idcardfacerecognition.sinosecu.com.cn";
        String path = "/api/faceliu.do";
        String method = "POST";
        String appcode = "1e93469bafdc438b9630565b35a70ff6";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("img1", img1);
        bodys.put("img2", img2);


        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
//            System.out.println(response.toString());
            //获取response的body
            String respStr = EntityUtils.toString(response.getEntity());
            System.out.println(respStr);
            JSONObject respObj = JSON.parseObject(respStr);
            JSONObject message = (JSONObject) respObj.get("message");
            Object status = message.get("status");
            if (status.equals("0") || status.equals(0))
            {
                JSONArray cardsinfo = (JSONArray)respObj.get("cardsinfo");
                JSONObject cardInfo = cardsinfo.getJSONObject(0);
                JSONArray items = (JSONArray)cardInfo.get("items");
                for (Object item : items) {
                    JSONObject itemObj = (JSONObject)item;
                    String desc = itemObj.getString("desc");
                    if (StringUtils.hasText(desc))
                    {
                        if (desc.equals("判定结果"))
                            return itemObj.getString("content").equals("是");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public BaseDto verify(String img1, int userId)
    {
        UserRealInfo userRealInfo = userRealInfoService.getPhotosByUserId(userId);
        String idCardFrontPhotoUrl = userRealInfo.getIdCardFrontPhotoUrl();
        if (!StringUtils.hasText(idCardFrontPhotoUrl))
            return BaseDto.error("实名认证失败");

        byte[] idCardFrontPhotoFileContent = userRealInfoService.getFileContent(userRealInfo.getIdCardFrontPhoto());

        boolean verify = this.verify(Base64Utils.encodeToString(idCardFrontPhotoFileContent), img1);
        BaseDto baseDto = new BaseDto();
        if (!verify)
        {
            baseDto.setCode(CodeConst.ERROR);
            baseDto.setMsg("人脸识别未通过");
        }
        else
        {
            baseDto.setData("success");
        }
        return baseDto;
    }

    public static void main(String[] args) {

    }
}
